package galleria.client;

import galleria.client.datatypes.Media;
import galleria.client.gui.GUI;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Image;

public class Model extends GWTGalleria {
	
	public Model() {
		getAlbum(currentAlbum);
	}
	
	/**
	 * this function gets all the images of a certain album in json format.
	 **/
	void getAlbum(String albumid) {
		
		String url = GWT.getHostPageBaseURL() + "backend/GWTGalleria.php?get=album&albumid="+albumid;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
		
		try {
			builder.sendRequest(null, new RequestCallback() {
		    public void onError(Request request, Throwable exception) {
		    	Window.alert("Could not load server data.");
		    }

		    public void onResponseReceived(Request request, Response response) {
		    	
		      if (response.getStatusCode() == 200) {
		    	  
		    	  if(response.getText().equals("no output")) {
		    		  new GUI("parameter missing.");
		    	  } else if(response.getText().equals("invalid")) {
		    		  new GUI("invalid query");
		    	  } else {
  
		    	  JSONValue JValue = JSONParser.parse(response.getText());						
					JSONObject JObject = JValue.isObject();
						
					for(int i = 1; i <= JObject.size(); i++) {
						JSONValue Iterator = JObject.get("" + i);
						JSONObject NewObject = Iterator.isObject();
						
						JSONValue Thumbnail = NewObject.get("thumbnail");
						JSONValue Fullsize = NewObject.get("fullsize");
						JSONValue photoId = NewObject.get("id");
						JSONValue descD = NewObject.get("desc_de");
						JSONValue descE = NewObject.get("desc_en");
						
						String ThumbnailPath = Thumbnail.toString().replaceAll("\"", "");
						String FullsizePath = Fullsize.toString().replaceAll("\"", "");
						String descDe = descD.toString().replaceAll("\"", "");;
						String descEn = descE.toString().replaceAll("\"", "");;
						String Id = photoId.toString().replaceAll("\"", "");;
						
						new Image(ThumbnailPath, 0, 0, 73, 73);
						new Image(FullsizePath);
						
						DataItem.add(new Media(Id, ThumbnailPath, FullsizePath, descDe, descEn));
					}
					
					new GUI(DataItem);
		    	  }
		      } else {
		    	  Window.alert(constants.servererror());
		      }
		    }       
		  });
		} catch (RequestException e) {
		  
		}
	}
}
